<?php

namespace App\Admin\Controllers;

use App\Models\Article;
use App\Models\ClinicCategory;
use App\Models\Doctor;
use App\Models\WorkRelateArticle;
use App\Models\WorkRoomSortCategory;
use App\Service\GreenCode;
use App\Util\Url;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use http\Env\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Route;
use PhpParser\Comment\Doc;
use Illuminate\Support\MessageBag;

class BenefitController extends AdminController
{

    public function __construct()
    {
        $doctor_id = Cache::get("doctor_id");
        $work_id = Cache::get("work_id");
        if (!$doctor_id || !$work_id) {
            return redirect(config('admin.route.prefix'));
        }
    }

    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '文章管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Article());
        $grid->fixColumns(0, 1);//固定列可滑动列表
        $grid->disableExport();//禁止导出
        //去掉复选框
//        $grid->disableRowSelector();
//        $grid->disableCreateButton();//禁用创建按钮
        $grid->actions(function ($actions) {
//            $actions->disableDelete(); //禁用删除按钮
//            $actions->disableEdit();//禁止行级编辑路由
            $actions->disableView();
        });
        $grid->filter(function ($filter) {
            // 去掉默认的id过滤器
            $filter->disableIdFilter();
            // 在这里添加字段过滤器
            //ID	视频名称	姓名
            $filter->like('article_title', __('文章名称'));
        });
//        $doctor_id = Cache::get("doctor_id");
//        $work_id = Cache::get("work_id");
        $work_id = session()->get("work_id");
        $doctor_id = session()->get("doctor_id");
        if(!$work_id || !$doctor_id){
            foreach($_COOKIE as $key => $value) {
                setcookie($key, $value, time() - 3600, '/');
            }
            return redirect("admin/auth/logout");
        }
        $where [] = ['doctor_id', '=', $doctor_id];//1公益2通告3其他
        $where [] = ['work_id', '=', $work_id];//1公益2通告3其他
//        $where [] = ['art_types', '=', 1];//1公益2通告3其他
        $grid->model()->where($where);//只读未审核和拒绝的
        $grid->model()->orderBy('id', 'desc');
        //1、发布人
        //2、发布时间
        $grid->column('id', __('Id'));
        $grid->column('article_title', __('文章标题'));
        $grid->column('is_original', __('文章来源'))->display(function () {
            $option = [
                1 => "原创",
                2 => "非原创"
            ];
            return $option[$this->is_original];
        });
        $grid->column('is_share', __('是否共享'))->display(function () {
            $option = [
                0 => "否",
                1 => "是",
            ];
            return $option[$this->is_share];
        });

        $grid->column('doctor.real_name', __('发布人'));
//        $grid->column('content', __('发布内容'));
        $grid->column('views', __('浏览量'));
        $grid->column('likes', __('点赞量'));
        $grid->column('created_at', __('发布时间'));

        /*$grid->column('sales', __('Sales'));
        $grid->column('views', __('Views'));
        $grid->column('likes', __('Likes'));
        $grid->column('article_score', __('Article score'));
        $grid->column('art_price', __('Art price'));
        $grid->column('isfee', __('Isfee'));
        $grid->column('is_use', __('Is use'));
        $grid->column('status', __('Status'));
        $grid->column('art_img', __('Art img'));
        $grid->column('author', __('Author'));
        $grid->column('sound', __('Sound'));
        $grid->column('created_at', __('Created at'));
        $grid->column('updated_at', __('Updated at'));
        $grid->column('art_types', __('Art types'));
        $grid->column('doctor_id', __('Doctor id'));
        $grid->column('clinic_cate_id', __('Clinic cate id'));
        $grid->column('is_original', __('Is original'));
        $grid->column('work_id', __('Work id'));*/

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Article::findOrFail($id));
        //查看禁止
        $show->panel()->tools(function ($tools) {
            $tools->disableDelete();//禁止删除
            $tools->disableEdit();//禁止修改
        });
        $show->field('id', __('Id'));
        $show->field('is_original', __('文章来源'))->as(function () {
            $option = [
                1 => "原创",
                2 => "非原创"
            ];
            return $option[$this->is_original];
        });

        $show->field('doctor.real_name', __('发布人'));

        $show->field('content', __('文章内容'));
        $show->field('sound', __('音频内容'))->unescape()->as(function (){

            if(!empty($this->sound)){
                return  '<video controls="音频内容" autoplay="true" name="media"><source src="'.Url::getHttpHost().'upload/'.$this->sound.'" type="audio/mpeg"></video>';
            }
        });
        $show->field('created_at', __('发布时间'));
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Article());
        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();//右上角删除
            $tools->disableView();//右上角查看
        });
        $form->html("<div style='color: red;font-size: 12px'>如您在发布文章时，点击发布按钮不成功，请更换浏览器后重试。<div style='float: right'><a target='_blank' href='/downloadstatic/upload_file_help_center.pdf' style='font-size: 12px;font-weight:bold ;color: red'>帮助文档</a></div></div>");
//        $doctor_id = Cache::get("doctor_id");
//        $work_id = Cache::get("work_id");
        $work_id = session()->get("work_id");
        $doctor_id = session()->get("doctor_id");
        $form->text('article_title', __('标题'))->required();

        $form->select('sales', '科室一级分类')->options(function () {
            return ClinicCategory::where('pid', 0)->pluck('classify_name', 'id'); //回显
        })->load('clinic_cate_id', '/index/getChild','id','classify_name');


        $form->select('clinic_cate_id', '科室二级分类')->options(function ($id) {
            return ClinicCategory::where('id', $id)->pluck('classify_name', 'id');//回显
        })->rules('required', ['required' => '必填',])->required();

        $form->select('self_cateid', __('本工作室分类'))->options((new WorkRoomSortCategory())->getSelfsOptions($work_id))->default(0)->rules('required')->required();;
        $form->hidden('art_types', __('类型'))->default(1)->required();;
//        $form->image('art_img', __('封面图'));
        $form->image('art_img', __('封面图'))->uniqueName()->removable()->required();//->rules('required');
        //$form->text('author', __('作者'));
        $form->radio('is_original', __('是否原创'))->options(['2' => '否', '1' => '是'])->default('1');
        $form->ueditor('content', __('内容'))->required();;
        $form->hidden('doctor_id', __('医生id'))->default($doctor_id);
        $form->hidden('work_id', __('工作室id'))->default($work_id);
//        $form->number('sales', __('Sales'));
//        $form->number('views', __('Views'));
//        $form->number('likes', __('Likes'));
//        $form->decimal('article_score', __('Article score'));
//        $form->decimal('art_price', __('Art price'));
//        $form->switch('isfee', __('Isfee'))->default(2);
//        $form->switch('is_use', __('Is use'));
        $form->radio('status', __('状态'))->options(['0' => '关闭', '1' => '正常'])->default('1');
        $form->radio('is_share', __('是否共享'))->options(['0' => '否', '1' => '是'])->default(0);
        $form->saving(function ($form){
            if(!is_numeric($form->clinic_cate_id) && !empty($form->clinic_cate_id)){
                $form->clinic_cate_id =  ClinicCategory::where([['pid','!=',0],['classify_name','=',$form->clinic_cate_id]])->value('id');
            }
            $doctor_id = session()->get("doctor_id");
            $author = (new Doctor())->where([['id','=',$doctor_id]])->value("real_name");
            if(empty($author)){
                $author = "平台发布";
            }
            $con = strip_tags(str_replace("&nbsp;",'',$form->content));
            $len  = mb_strlen($con);
            if($len >1500){
//                计算分页处理
                $total = intval(ceil($len / 1500));
                for($i = 1;$i<=$total;$i++){
                    $page = ($i-1) * 1500;
                    $str = mb_substr($con,$page,1500);
                    $dt = (new GreenCode())->getWordCodeInfo($str);
                    if($dt === '408'){
                        $error = new MessageBag([
                            'title' => '温馨提示',
                            'message' => '文字检索系统可能欠费请联系平台人员进行续费!',
                        ]);
                        return back()->with(compact('error'));
                    }
                    if($dt !== true){
                        $error = new MessageBag([
                            'title' => '温馨提示',
                            'message' => $dt.'涉及敏感词汇,不允许提交',
                        ]);
                        return back()->with(compact('error'));
                    }
                }
            }else{
                $dt = (new GreenCode())->getWordCodeInfo($con);
                if($dt === '408'){
                    $error = new MessageBag([
                        'title' => '温馨提示',
                        'message' => '文字检索系统可能欠费请联系平台人员进行续费!',
                    ]);
                    return back()->with(compact('error'));
                }
                if($dt !== true){
                    $error = new MessageBag([
                        'title' => '温馨提示',
                        'message' => $dt.'涉及敏感词汇,不允许提交',
                    ]);
                    return back()->with(compact('error'));
                }
            }
            $form->model()->setAttribute('author', $author);
            if (Route::currentRouteName() == 'admin.benefit.update') {
                $info = (new Article())->where([['id','=',$form->model()->id]])->first();
                $art = new WorkRelateArticle();
                $relate_article = $art->where([['article_id','=',$info->id],['work_id','=',$info->work_id],['cate_id','=',$info->self_cateid]])->first();
                if($relate_article){
                    $relate_article->article_id = $info->id;
                    $relate_article->work_id =session()->get("work_id");
                    $relate_article->cate_id = $form->model()->self_cateid;
                    $relate_article->save();
                }else{
                    $article_id = $form->model()->id;
                    $art->article_id = $article_id;
                    $art->work_id = session()->get("work_id");
                    $art->cate_id = $form->model()->self_cateid;
                    $art->save();
                }
            }
        });
        $form->saved(function ($form){
            $art = new WorkRelateArticle();
            if ($form->model()->self_cateid) {
                $article_id = $form->model()->id;
                $art->where([['article_id','=',$article_id],['work_id','=',session()->get("work_id")]])->delete();
                $art->article_id = $article_id;
                $art->work_id = session()->get("work_id");;
                $art->cate_id = $form->model()->self_cateid;
                $art->save();
            }
        });
        return $form;
    }


    public function destroy($id)
    {
        $info = (new Article())->where([['id','=',$id]])->first();
        (new WorkRelateArticle())->where([['article_id','=',$id],['work_id','=',$info->work_id],['cate_id','=',$info->self_cateid]])->delete();
        return parent::destroy($id);
    }
}
